import { login } from "./request.js";
//获取注册按钮
let registerBtn = document.querySelector("#registerBtn");
//获取查看预约按钮
let seeBtn = document.querySelector(".see");
let username = document.querySelector('#username');
let phone = document.querySelector('#phone');
let cardId = document.querySelector('#cardId');
let skChase = document.querySelector('.sk-chase');
let flag = true;

//验证用户名正则
let reg1 = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/;
//验证手机号
let reg2 = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
//验证身份证号
let reg3 = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
let arr = [reg1, reg2, reg3, reg3];
//失去焦点验证
let ipts = document.querySelectorAll('input');
ipts.forEach(function (ele, index) {
    ele.addEventListener('blur', function () {
        checkValue(ele, index, arr);
    })
})
//点击按钮触发验证
registerBtn.addEventListener('click', async function (e) {
    e.preventDefault();
    flag = true;
    //这里验证是为了防止没有填信息就点击的情况
    ipts.forEach(function (ele, index) {
        checkValue(ele, index, arr);
    })
    if (flag) {
        skChase.style.display = "block";
        let data = {};
        data.name = username.value;
        data.phone = phone.value;
        data.card = cardId.value;
        let res = await login(data);
        if (res.msg == "登录成功") {
            sessionStorage.setItem('token', res.result.token);
            sessionStorage.setItem('name', username.value);
            sessionStorage.setItem('phone', phone.value);
            skChase.style.display = "none";
            location.href = `./html/chooseday.html`;
        }
    }

})
//验证函数
function checkValue(input, index, arr) {
    if (input.value == '') {
        flag = false;
        error(input, `该项为必填项`);
    } else if (!arr[index].test(input.value)) {
        flag = false;
        error(input, `格式错误`);
    } else {
        success(input);
    }

}
//错误提示框
function error(input, msg) {
    //input是改变的节点
    //msg 是改变的提示文案
    input.parentNode.className = "ipt error";
    input.nextElementSibling.innerHTML = msg;
}
//格式正确
function success(input) {
    //input是改变的节点
    //msg 是改变的提示文案
    input.parentNode.className = "ipt success";
}

//查看预约记录
seeBtn.addEventListener('click', async function () {

    ipts.forEach(function (ele, index) {
        checkValue(ele, index, arr);
    })
    if (flag) {
        skChase.style.display = "block";
        let data = {};
        data.name = username.value;
        data.phone = phone.value;
        data.card = cardId.value;
        let res = await login(data);
        if (res.msg == "登录成功") {
            sessionStorage.setItem('token', res.result.token);
            sessionStorage.setItem('phone', phone.value);
            sessionStorage.setItem('name', username.value);
            skChase.style.display = "none";
            location.href = './html/history.html';
        }
    }

})
